Remove Cart Items Based on Specific Conditions in WooCommerce

Remove Cart Items Based on Specific Conditions in WooCommerce

To remove cart items conditionally in WooCommerce, you can use the woocommerce_before_calculate_totals hook. This hook is triggered when the cart totals are being calculated, so you can use it to modify the cart contents before the totals are calculated.

Suggested Read: How to check if a product is in a WooCommerce order

Method-1: Remove cart items conditionally based on a Product ID

Here’s an example of how you can remove cart items conditionally based on a custom field:

In this example, we’re assigning a product id named “remove_product_id”. We loop through each cart item and get the value of the product id. If the product id value meets our condition, we remove the cart item using the remove_cart_item() method.

You can modify this code to check for any condition you like, such as the quantity of an item or the product category. Just adjust the conditional statement in the loop to suit your needs.

Are you want to get implementation help, or modify or extend the functionality of this script?

A Tutorialswebsite Expert can do it for you.

Method-2: Remove cart items conditionally based on the price

Here’s an example code snippet that removes items from the cart if their price is less than a certain amount:

In this example, the remove_items_from_cart function is hooked to the woocommerce_before_calculate_totals action. It checks if the user is not an administrator and if the request is not an AJAX request, to ensure that it only affects the front-end cart.

Then it loops through each item in the cart and gets its price. If the price is less than the specified minimum price, it removes the item from the cart using the $cart->remove_cart_item method.

You can modify this code to suit your specific needs, such as checking for a certain product category or tag or using a different condition to determine whether an item should be removed from the cart.

Also Read: Woocommerce hook to display offers text after shop loop item

Wrapping Words

Thanks for reading 🙏, I hope you found the How to Remove Cart Items Based on Specific Conditions in WooCommerce tutorial helpful for your project. Keep learning! If you face any problems – I am here to solve your problems.

Related posts